package com.wzapp.sitposture.common.base;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

@Service
public class SpringContextHolder implements ApplicationContextAware {

	private SpringContextHolder() {
	}

	/**
	 * Spring应用上下文
	 */
	private static ApplicationContext APPLIACTION_CONTEXT;

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		// 实现ApplicationContextAware接口的回调方法，设置上下文环
		setApplicationContextInner(applicationContext);
	}

	private static void setApplicationContextInner(ApplicationContext applicationContext) {
		APPLIACTION_CONTEXT = applicationContext;
	}

	public static ApplicationContext getApplicationContext() {
		return APPLIACTION_CONTEXT;
	}

	/**
	 * 获取对象 这里重写了bean方法，起主要作用
	 *
	 * @param beanId
	 * @param <T>
	 *            t
	 * @return T
	 * @throws BeansException
	 *             BeansException
	 */
	@SuppressWarnings("unchecked")
	public static <T> T getBean(String beanId) throws BeansException {
		return (T) APPLIACTION_CONTEXT.getBean(beanId);
	}

	/**
	 * @param clazz
	 *            Class<T>
	 * @param <T>
	 *            t
	 * @return <T> T
	 * @throws BeansException
	 *             BeansException
	 * @author ql
	 */
	public static <T> T getBean(Class<T> clazz) throws BeansException {
		return APPLIACTION_CONTEXT.getBean(clazz);
	}

}
